<?php
namespace app\techn_api\controller\v1;
use think\Db;
use app\service\PaymentService;
use app\service\OrderService;
use app\service\UserWeixinService;
use app\service\TechnWeixinService;
use app\service\TechnService;
class Order extends Base
{
	public function _initialize()
	{
		parent::_initialize();
		$this->IsLogin(); //验证登录
		$this->IsTechn(); //验证技师
	}

	/**
	 * 获取订单列表
	 */
	public function lists()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		//dump($params);
		//表单验证
		$validate = $this->validate(
			$params,
			[
				'status' => 'require',
				'page' => 'require'
			],
			[
				'status.require' => '状态有误',
				'page.require' => '分页有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        $map = [
        	'techn_id' => $params['techn']['id'],
        	'order_model' => 0,
        	'pay_status' => ['EGT', 1]
        ];
        $stop = Db::name('stop')->where('id',1)->find();
        if ($stop['pian_status'] == 1){
            $result['code'] = -1;
            $result['msg'] = "暂无数据";
            echo json_encode($result);
            exit;
        }
        if($params['status'] > 0)
        {
        	switch ($params['status']) {
        		//待接单
        		case 1:
        		    $map['status'] = 1;
        		break;
        		//待服务
        		case 2:
        		    $map['status'] = ['in', '2,3,4'];
        	    break;
        	    //服务中
        	    case 3:
        	        $map['status'] = 5;
        	    break;
        	    //已完成
        	    case 4:
        	        $map['status'] = 6;
        	    break;
        	    //待补单
        	    case 5:
        	    	$map['techn_is_repair'] = 1;
        	    	$map['techn_repair_sid'] = 0;
        	    break;
        	}
        }
        // $list_data = Db::name('order')->where($map)->order('status asc, pre_start_time asc')->limit(($params['page']-1)*10,10)->select();
        $list_data = Db::name('order')->where($map)->order('add_time desc')->limit(($params['page']-1)*10,10)->select();
        if(!empty($list_data))
        {
        	//订单状态
        	$status_array = OrderService::$status_array;
        	//遍历处理
        	foreach($list_data as $key => $value)
        	{
        		//订单状态
        		$list_data[$key]['status_name'] = !empty($status_array[$value['status']]['name']) ? $status_array[$value['status']]['name'] : '';
        		//查询订单详情
        		$order_detail = Db::name('order_detail')->where(['order_id' => $value['id'],'showtype'=>1])->select();
        		if(!empty($order_detail))
        		{
        			foreach($order_detail as $k => $v)
        			{
        				$order_detail[$k]['images'] = request()->domain().$v['images'];
        			}
        		}
        		$list_data[$key]['order_detail'] = $order_detail;
        		//查询服务技师
        		$techn_info = Db::name('techn')->field('nickname')->where(['id' => $value['techn_id']])->find();
        		$list_data[$key]['techn_info'] = $techn_info;
        		//预约时间
        		$list_data[$key]['pre_start_time_time'] = !empty($value['pre_start_time']) ? date('Y-m-d H:i:s', $value['pre_start_time']) : '';
        		
        		
                $list_data[$key]['contact_type']=2;
                if($value['status']>=2&&$value['status']<=5){
                    $list_data[$key]['contact_type']=1;
                }elseif($value['status']==6&&time()-$value['pre_end_time']<600){
                    $list_data[$key]['contact_type']=1;
                }
        	}
        	$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data'] = $list_data;
	        $result['from'] = db::name('from')->where('is_delete_time',0)->select();
        }else
        {
        	$result['code'] = -1;
	        $result['msg'] = "暂无数据";
        }
        echo json_encode($result);
	}

	/**
	 * 获取订单情详
	 */
	public function detail()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        //订单状态
        $status_array = OrderService::$status_array;
        $order_info['status_name'] = !empty($status_array[$order_info['status']]['name']) ? $status_array[$order_info['status']]['name'] : '';
        //查询订单状态历史记录
        $status_history = Db::name('order_status_history')->where(['order_id' => $order_info['id']])->select();
        $new_status_history = [];
        foreach($status_history as $key => $value)
        {
        	$value['extension_data'] = !empty($value['extension_data']) ? json_decode($value['extension_data'], true) : [];
        	if(!empty($value['extension_data']['images']))
        	{
        		$value['extension_data']['images'] = explode(",", $value['extension_data']['images']);
        	}
        	$new_status_history[$value['new_status']] = $value;
        }
        //dump($new_status_history);
        //die();
        $order_info['status_history'] = $new_status_history;
        //查询订单详情服务项目
        $order_detail = Db::name('order_detail')->where(['order_id' => $order_info['id'],'showtype'=>1])->select();
        if(!empty($order_detail))
		{
			foreach($order_detail as $k => $v)
			{
			    $msgs='';
			    if($v['type']==1){
			        $msgs='(加钟)';
			    }
				$order_detail[$k]['title'] = $v['title'].$msgs;
				$order_detail[$k]['images'] = request()->domain().$v['images'];
			}
		}
		$order_info['order_detail'] = $order_detail;
		//查询服务技师
		$order_info['techn_info'] = Db::name('techn')->field('nickname')->where(['id' => $order_info['techn_id']])->find();
		//查询订单地址
		$order_address = Db::name('order_address')->where(['order_id' => $order_info['id']])->find();
		if(!empty($order_address))
		{
			$order_address['star_mobile'] = substr_replace($order_address['mobile'], '****', 3, 4);
		}
		$order_info['order_address'] = $order_address;
		//下单时间
		$order_info['add_time_time'] = !empty($order_info['add_time']) ? date('Y-m-d H:i', $order_info['add_time']) : '';
		//预约服务时间
		$order_info['pre_start_time_time'] = !empty($order_info['local_pre_start_time']) ? date('Y-m-d H:i', $order_info['local_pre_start_time']) : date('Y-m-d H:i', $order_info['pre_start_time']);
		//预约服务结束时间
		$order_info['pre_end_time_time'] = !empty($order_info['local_pre_end_time']) ? date('Y-m-d H:i', $order_info['local_pre_end_time']) : date('Y-m-d H:i', $order_info['pre_end_time']);
		//支付方式
		$payment_array = PaymentService::$payment_array;
		$order_info['payment_name'] = !empty($payment_array[$order_info['payment_id']]['name']) ? $payment_array[$order_info['payment_id']]['name'] : '';
		//技师接单时间
		$order_info['meet_time_time'] = !empty($order_info['meet_time']) ? date('Y-m-d H:i:s', $order_info['meet_time']) : '';
		//技师出发时间
		$order_info['leave_time_time'] = !empty($order_info['leave_time']) ? date('Y-m-d H:i:s', $order_info['leave_time']) : '';
		//技师到达时间
		$order_info['arrive_time_time'] = !empty($order_info['arrive_time']) ? date('Y-m-d H:i:s', $order_info['arrive_time']) : '';
		//开始服务时间
		$order_info['service_time_time'] = !empty($order_info['service_time']) ? date('Y-m-d H:i:s', $order_info['service_time']) : '';
		//服务完成时间
		$order_info['over_time_time'] = !empty($order_info['over_time']) ? date('Y-m-d H:i:s', $order_info['over_time']) : '';
		
        $order_info['from'] = db::name('from')->where('is_delete_time',0)->select();
	        
        $order_info['contact_type']=2;
        if($order_info['status']>=2&&$order_info['status']<=5){
            $order_info['contact_type']=1;
        }elseif($order_info['status']==6&&time()-$order_info['pre_end_time']<600){
            $order_info['contact_type']=1;
        }

        $balance = Db::name('balance')->where('order_id',$params['order_id'])->where('balance_type','<>',2)->where('identity_type','<>','techn')->select();

        $techn_divide = Db::name('balance')->where('order_id',$params['order_id'])->where('balance_type',1)->where('identity_type','techn')->value('divide_into');
        $msg = array_column($balance,'msg');
        $divide = array_column($balance,'divide_into');
        $lang = '比例 : 技师分成:'.$techn_divide.'%';


        if ($order_info['preferential_price'] >0){
            $lang .= '优惠券:￥'.($order_info['preferential_price']*$techn_divide/100 ).' ';

        }else{
            $lang .= '优惠券:￥0 ';

        }
//        if (in_array('平台分成',$msg)){
//            $pingtai = Db::name('balance')
//                ->where('order_id',$params['order_id'])
//                ->where('balance_type','<>',2)
//                ->where('identity_type','<>','techn')
//                ->where('msg','平台分成')
//                ->sum('no_money');
//            if ($pingtai > 0){
//                $lang .= '，平台分成 ： ￥'.$pingtai;
//            }
//        }
        $qudao = 0;

        if (in_array('用户分佣',$msg)){
            $pingtai = Db::name('balance')
                ->where('order_id',$params['order_id'])
                ->where('balance_type','<>',2)
                ->where('identity_type','<>','techn')
                ->where('msg','用户分佣')
                ->sum('no_money');
            $qudao += $pingtai * $techn_divide /100;
        }
        if (in_array('技师分佣',$msg)) {
            $pingtai = Db::name('balance')
                ->where('order_id', $params['order_id'])
                ->where('balance_type', '<>', 2)
                ->where('identity_type', '<>', 'techn')
                ->where('msg', '技师分佣')
                ->sum('no_money');
            $qudao += $pingtai * $techn_divide /100;
        }
        if (in_array('业务员分拥',$msg)) {
            $pingtai = Db::name('balance')
                ->where('order_id', $params['order_id'])
                ->where('balance_type', '<>', 2)
                ->where('identity_type', '<>', 'techn')
                ->where('msg', '业务员分拥')
                ->sum('no_money');
            $qudao += $pingtai * $techn_divide /100;
        }
        if ($qudao > 0){
            $lang .= '渠道扣费:￥'.$qudao.' ';
        }else{
            $lang .= '渠道扣费:￥0 ';
        }

//        if (in_array('机构分成',$msg)){
//            $pingtai = Db::name('balance')
//                ->where('order_id',$params['order_id'])
//                ->where('balance_type','<>',2)
//                ->where('identity_type','<>','techn')
//                ->where('msg','机构分成')
//                ->sum('no_money');
//            if ($pingtai > 0){
//                $lang .= ' 机构分成 ： ￥'.$pingtai;
//            }else{
//                $lang .= ' 机构分成 ： ￥0';
//
//            }
//        }else{
//            $lang .= ' 机构分成 ： ￥0';
//        }


        $techn_shou = Db::name('balance')->where('order_id',$params['order_id'])->where('identity_type','techn')->sum('no_money');
        $lang .= '。';
        $order_info['balance'] = $lang;
        $order_info['balance_list'] = $balance;
        $order_info['techn_shou'] = $techn_shou;


		$result['code'] = 0;
        $result['msg'] = "请求成功";
        $result['data'] = $order_info;
        echo json_encode($result);
	}

	/**
	 * 立即接单
	 */
	public function yes_meet()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id'], 'techn_id' => $params['techn']['id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if($order_info['status'] != 1)
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        //技师与下单人绑定隐私电话
        //查询下单人的电话
        //$order_address_info = Db::name('order_address')->where(['order_id' => $order_info['id']])->find();
        //绑定关系
        //$args = ["poolKey" => "FC100000167170034","phoneNoA" => $params['techn']['mobile'],"phoneNoB" => $order_address_info['mobile'],"expiration" => date('Y-m-d H:i:s', time()+(1*24*60*60)), "isRecordingEnabled" => true];
        //$yinsi_res = \yinsi\Privacy::bindAxb($args);

        //开启事务
        Db::startTrans();
        $upd_data = [
        	'status' => 2,
        	'meet_status' => 1,
        	'meet_time' => time(),
        	'upd_time' => time(),
        	//'subs_id' => $yinsi_res['code'] == 1 ? $yinsi_res['subsId'] : '',
        	//'secret_no' => $yinsi_res['code'] == 1 ? $yinsi_res['secretNo'] : '',
        ];
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($upd_data))
        {
        	//事务回滚
        	Db::rollback();
        	echo json_encode(['code' => -1, 'msg' => '接单失败']);
        	exit();
        }

        // 订单状态日志添加
        $status_array = OrderService::$status_array;
        $order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $upd_data['status'],
			'msg' => '技师接单['.$status_array[$order_info['status']]['name'].'-'.$status_array[$upd_data['status']]['name'].']',
			'identity_type' => 'techn',
			'identity_id' => $params['techn']['id'],
			'add_time' => time()
		]);

		if($order_status_history_id <= 0)
		{
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '接单失败']);
            exit();
		}
		//提交事务
		Db::commit();
		echo json_encode(['code' => 0, 'msg' => '接单成功']);

		//给用户发送模板消息
		//查询用户的openid
		$openid = Db::name('user_weixin')->where(['user_id' => $order_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
		if(!empty($openid))
		{
	        /////////////上方测试，下方正式/////////
	        //查询订单详情
	        $order_detail_title = Db::name('order_detail')->where(['order_id' => $order_info['id']])->column('title');
	       // $order_detail_title = implode(',', $order_detail_title);
	        $order_detail_title_new='服务项目:'.implode(',',$order_detail_title);
		      //  foreach ($order_detail_title as $k=>$v){
		      //      $order_detail_title_new.="\n ".($k+1).'.'.$v;
		      //  }
	        $tem_msg['touser'] = $openid;
	        $tem_msg['template_id'] = '0AKe-kYOFFklpG22aP1oiAIS76v8pIh5_xBNbGbZUck';
	        $tem_msg['url'] = request()->domain().'/h5/pages/order/orderdetail?order_id='.$order_info['id'];
	        $tem_msg['data'] = [
	            'first' => [
	                'value' => '技师已接受您的订单，技师将会尽快与您取得联系，请保持手机畅通',
	                'color' => '#173177'
	            ],
	            'keyword1' => [
	                'value' => $order_info['order_no'],
	                'color' => '#173177'
	            ],
	            'keyword2' => [
	                'value' => $order_detail_title_new,
	                'color' => '#173177'
	            ],
	            'keyword3' => [
	                'value' => $params['techn']['nickname'],
	                'color' => '#173177'
	            ],
	            'remark' => [
	                'value' => '感谢您的使用！',
	                'color' => '#173177'
	            ]
	        ];

	        UserWeixinService::send_wx_web_tem_msg($tem_msg);
		}
		
		
        TechnService::TechnPreTimey($params['techn']['id']);

	}

	/**
	 * 确认出发
	 */
	public function leave()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //判断技师实时地址
        if(empty($params['techn_last_address']))
        {
        	echo json_encode(['code' => -1, 'msg' => '请授权当前地址']);
            exit();
        }

        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id'], 'techn_id' => $params['techn']['id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if($order_info['status'] != 2)
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        //开启事务
        Db::startTrans();
        $upd_data = [
        	'status' => 3,
        	'leave_time' => time(),
        	'upd_time' => time()
        ];
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($upd_data))
        {
        	//事务回滚
        	Db::rollback();
        	echo json_encode(['code' => -1, 'msg' => '出发失败']);
        	exit();
        }
        // 订单状态日志添加
        $extension_data = [
        	'address' => $params['techn_last_address']
        ];
        $status_array = OrderService::$status_array;
        $order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $upd_data['status'],
			'msg' => '技师出发['.$status_array[$order_info['status']]['name'].'-'.$status_array[$upd_data['status']]['name'].']',
			'identity_type' => 'techn',
			'identity_id' => $params['techn']['id'],
			'extension_data' => json_encode($extension_data, JSON_UNESCAPED_UNICODE),
			'add_time' => time()
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '出发失败']);
            exit();
		}
		
		
        TechnService::TechnPreTimey($params['techn']['id']);
		//更新技师实时数据信息
		/*$techn_last_data = [
			'province' => $params['techn_last_address']['province'],
			'city' => $params['techn_last_address']['city'],
			'county' => $params['techn_last_address']['county'],
			'province_name' => $params['techn_last_address']['province_name'],
			'city_name' => $params['techn_last_address']['city_name'],
			'county_name' => $params['techn_last_address']['county_name'],
			'address' => $params['techn_last_address']['address'],
			'lng' => $params['techn_last_address']['lng'],
			'lat' => $params['techn_last_address']['lat'],
			'upd_time' => time()
		];
		if(!Db::name('techn_last')->where(['techn_id' => $params['techn']['id']])->update($techn_last_data))
		{
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '出发失败']);
            exit();
		}*/
		//提交事务
		Db::commit();
		echo json_encode(['code' => 0, 'msg' => '出发成功']);
	}

	/**
	 * 确认到达
	 */
	public function arrive()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //判断技师实时地址
        if(empty($params['techn_last_address']))
        {
        	echo json_encode(['code' => -1, 'msg' => '请授权当前地址']);
            exit();
        }
        //判断技师拍照打卡
        if(empty($params['techn_last_images']))
        {
        	echo json_encode(['code' => -1, 'msg' => '请拍照']);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id'], 'techn_id' => $params['techn']['id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if($order_info['status'] != 3)
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        //开启事务
        Db::startTrans();
        $upd_data = [
        	'status' => 4,
        	'arrive_time' => time(),
        	'upd_time' => time()
        ];
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($upd_data))
        {
        	//事务回滚
        	Db::rollback();
        	echo json_encode(['code' => -1, 'msg' => '到达失败']);
        	exit();
        }
        // 订单状态日志添加
        $extension_data = [
        	'address' => $params['techn_last_address'],
        	'images' => implode(",", $params['techn_last_images'])
        ];
        $status_array = OrderService::$status_array;
        $order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $upd_data['status'],
			'msg' => '技师到达['.$status_array[$order_info['status']]['name'].'-'.$status_array[$upd_data['status']]['name'].']',
			'identity_type' => 'techn',
			'identity_id' => $params['techn']['id'],
			'extension_data' => json_encode($extension_data, JSON_UNESCAPED_UNICODE),
			'add_time' => time()
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '到达失败']);
            exit();
		}
		
		
        TechnService::TechnPreTimey($params['techn']['id']);
		//更新技师实时数据信息
		/*$techn_last_data = [
			'province' => $params['techn_last_address']['province'],
			'city' => $params['techn_last_address']['city'],
			'county' => $params['techn_last_address']['county'],
			'province_name' => $params['techn_last_address']['province_name'],
			'city_name' => $params['techn_last_address']['city_name'],
			'county_name' => $params['techn_last_address']['county_name'],
			'address' => $params['techn_last_address']['address'],
			'lng' => $params['techn_last_address']['lng'],
			'lat' => $params['techn_last_address']['lat'],
			'upd_time' => time()
		];
		if(!Db::name('techn_last')->where(['techn_id' => $params['techn']['id']])->update($techn_last_data))
		{
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '到达失败']);
            exit();
		}*/
		//提交事务
		Db::commit();
		echo json_encode(['code' => 0, 'msg' => '到达成功']);
	}

	/**
	 * 开始服务
	 */
	public function start_service()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id'], 'techn_id' => $params['techn']['id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if($order_info['status'] != 4)
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        //开启事务
        Db::startTrans();
        $pre_start_time = time();
        
        $upd_data = [
        	'status' => 5,
        	
        	'service_time' => $pre_start_time,
        	'upd_time' => $pre_start_time,
        	'pre_start_time'=>$pre_start_time,
        	'pre_end_time'=>$pre_start_time+$order_info['pre_end_time']-$order_info['pre_start_time'],
        	'local_pre_start_time'=>$order_info['pre_start_time'],
        	'local_pre_end_time'=>$order_info['pre_end_time'],
        ];
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($upd_data))
        {
        	//事务回滚
        	Db::rollback();
        	echo json_encode(['code' => -1, 'msg' => '开始服务失败']);
        	exit();
        }
        // 订单状态日志添加
        $status_array = OrderService::$status_array;
        $order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $upd_data['status'],
			'msg' => '技师开始服务['.$status_array[$order_info['status']]['name'].'-'.$status_array[$upd_data['status']]['name'].']',
			'identity_type' => 'techn',
			'identity_id' => $params['techn']['id'],
			'extension_data' => '',
			'add_time' => time()
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '开始服务失败']);
            exit();
		}
		
		
		//走队列 提醒还有5分钟结束
		//创建任务： 项目命名空间\模块\文件夹\控制器@方法
		$job = "app\service\QueuesService@order_fw_close";
		//延时时间
		$delayed_second = $order_info['pre_end_time']-$order_info['pre_start_time']-300;
		$queues_data = ['id' => $params['order_id']];
		\think\Queue::later($delayed_second, $job, $queues_data, 'order_fw_close');
		
        TechnService::TechnPreTimey($params['techn']['id']);
		
		//提交事务
		Db::commit();
		echo json_encode(['code' => 0, 'msg' => '开始服务成功']);
	}

	/**
	 * 确认完成服务
	 */
	public function over()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		$validate = $this->validate(
			$params,
			[
                'order_id' => 'require',
//                'xing' => 'require',
//                'yuan' => 'require',
			],
			[
				'order_id.require' => '订单id有误',
//				'xing.require' => '选择星级',
//				'yuan.require' => '选择客户来源',
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        $xing = !empty($params['xing'])?$params['xing']:'';
        $yuan = !empty($params['yuan'])?$params['yuan']:'';

        unset($params['xing']);
        unset($params['yuan']);

        if(empty($params['status'])){
        //判断技师实时地址
        if(empty($params['techn_last_address']))
        {
        	echo json_encode(['code' => -1, 'msg' => '请授权当前地址']);
            exit();
        }
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id'], 'techn_id' => $params['techn']['id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if($order_info['status'] != 5 && empty($params['status']))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        //开启事务
        Db::startTrans();
        $status=6;
        $budan_reason='';
        if(!empty($params['status'])){
            if(time()-$order_info['arrive_time']<1200){
            	echo json_encode(['code' => -1, 'msg' => '不足20分钟,不可操作']);
                exit();
            }
            $status=9;
            $budan_reason=$params['budan_reason'];
            if(empty($budan_reason)){
            	echo json_encode(['code' => -1, 'msg' => '请输入原因']);
                exit();
            }
        }
        
        
        
        $upd_data = [
        	'status' => $status,
        	'over_time' => time(),
        	'upd_time' => time(),
        	'budan_reason'=>$budan_reason
        ];
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($upd_data))
        {
        	//事务回滚
        	Db::rollback();
        	echo json_encode(['code' => -1, 'msg' => '完成失败']);
        	exit();
        }
        // 订单状态日志添加
        $extension_data = [
        	'address' => $params['techn_last_address']
        ];
        $ordermsg='';
        if($status==9){
            $ordermsg='-补单';
        }
        $status_array = OrderService::$status_array;
        $order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $upd_data['status'],
			'msg' => '技师完成服务['.$status_array[$order_info['status']]['name'].'-'.$status_array[$upd_data['status']]['name'].']'.$ordermsg,
			'identity_type' => 'techn',
			'identity_id' => $params['techn']['id'],
			'extension_data' => json_encode($extension_data, JSON_UNESCAPED_UNICODE),
			'add_time' => time()
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '完成失败']);
            exit();
		}
		//更新技师实时数据信息
		/*$techn_last_data = [
			'province' => $params['techn_last_address']['province'],
			'city' => $params['techn_last_address']['city'],
			'county' => $params['techn_last_address']['county'],
			'province_name' => $params['techn_last_address']['province_name'],
			'city_name' => $params['techn_last_address']['city_name'],
			'county_name' => $params['techn_last_address']['county_name'],
			'address' => $params['techn_last_address']['address'],
			'lng' => $params['techn_last_address']['lng'],
			'lat' => $params['techn_last_address']['lat'],
			'upd_time' => time()
		];
		if(!Db::name('techn_last')->where(['techn_id' => $params['techn']['id']])->update($techn_last_data))
		{
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '完成失败']);
            exit();
		}*/
        //处理技师评价客户
        if(!empty($xing) && !empty($yuan)){
            $user_pingjia = [
                'xing' => $xing,
                'yuan' => $yuan,
                'order_id' => $order_info['id'],
                'user_id' => $order_info['user_id'],
                'techn_id' => $order_info['techn_id'],
                'add_time' => time(),
            ];
            Db::name('user_pingjia')->insert($user_pingjia);
        }


		//处理结算信息
		$balance_list = Db::name('balance')->where(['order_id' => $order_info['id'], 'status' => 0])->select();
		if(empty($balance_list))
		{
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '结算数据不存在']);
            exit();
		}
		$balance_ph_count = 0;
        $over_result = 0;
		foreach($balance_list as $key => $value)
		{
			switch($value['identity_type'])
			{
				//技师
				case 'techn':
				    //获取技师余额
			        $techn_info = Db::name('techn')->where(['id' => $value['identity_id']])->find();
			        if(empty($techn_info))
					{
						continue;
					}
                    if ($value['balance_type'] != 2){
                        $over_result += $value['no_money'];
                    }
					// 更新余额数据
					$techn_money_data = [
						'money' => Db::raw('money+'.$value['no_money']),
			            'upd_time' => time()
					];

					if(!Db::name('techn')->where(['id' => $techn_info['id']])->update($techn_money_data))
					{
						continue;
					}
					//技师余额日志
					$techn_money_log_id = Db::name('money_log')->insertGetId([
			            'identity_type' => 'techn',
			            'identity_id' => $techn_info['id'],
			            'business_type' => $value['balance_type'] == 2 ? 4 : 5,
			            'money_type' => 0,
			            'operation_type' => 1,
			            'operation_money' => $value['no_money'],
			            'original_money' => $techn_info['money'],
			            'latest_money' => $techn_info['money']+$value['no_money'],
			            'from_order_id' => $order_info['id'],
			            'msg' => '技师'.($value['balance_type'] == 2 ? '出行' : '服务').'费用',
			            'add_time' => time()
			        ]);
			        if($techn_money_log_id <= 0)
			        {
			        	continue;
			        }
			        //更新当前结算信息状态
			        if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
					{
						continue;
					}
				break;
				//机构
				case 'proxy':
				    //获取机构余额
				    $proxy_info = Db::name('proxy')->where(['proxy_id' => $value['identity_id']])->find();
				    if(empty($proxy_info))
					{
						continue;
					}
                    $over_result += $value['no_money'];
					// 更新余额数据
					$proxy_money_data = [
						'money' => Db::raw('money+'.$value['no_money']),
			            'upd_time' => time()
					];

					if(!Db::name('proxy')->where(['proxy_id' => $proxy_info['proxy_id']])->update($proxy_money_data))
					{
						continue;
					}
					//机构余额日志
					$proxy_money_log_id = Db::name('money_log')->insertGetId([
			            'identity_type' => 'proxy',
			            'identity_id' => $proxy_info['proxy_id'],
			            'business_type' => 5,
			            'money_type' => 0,
			            'operation_type' => 1,
			            'operation_money' => $value['no_money'],
			            'original_money' => $proxy_info['money'],
                        'from_order_id' => $order_info['id'],
			            'latest_money' => $proxy_info['money']+$value['no_money'],
			            'msg' => '机构服务分成费用',
			            'add_time' => time()
			        ]);
			        if($proxy_money_log_id <= 0)
			        {
			        	continue;
			        }
			        //更新当前结算信息状态
			        if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
					{
						continue;
					}
				break;
				//系统
				case 'system':
                    $over_result += $value['no_money'];

				    //更新当前结算信息状态
			        if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
					{
						continue;
					}
				break;
				//用户
				case 'user':
				    //获取用户佣金
				    $info = Db::name('user')->where(['id' => $value['identity_id']])->find();
				    if(empty($info))
					{
						continue;
					}

                    $over_result += $value['no_money'];

					if($value['khtype']==1){
					    // 更新余额数据
    					$user_money_data = [
    						'yongjin' => Db::raw('yongjin+'.$value['no_money']),
    			            'upd_time' => time()
    					];
    					if(!Db::name('user')->where(['id' => $value['identity_id']])->update($user_money_data))
    					{
    						continue;
    					}
					}else{
					    // 更新余额数据
    					$user_money_data = [
    						'yongjin2' => Db::raw('yongjin2+'.$value['no_money']),
    			            'upd_time' => time()
    					];

    					if(!Db::name('user')->where(['id' => $value['identity_id']])->update($user_money_data))
    					{
    						continue;
    					}
					}
					
					
					
					//余额日志
					$proxy_money_log_id = Db::name('money_log')->insertGetId([
			            'identity_type' => 'user',
			            'identity_id' => $info['id'],
			            'business_type' => 7,
			            'money_type' => 0,
			            'operation_type' => 1,
			            'operation_money' => $value['no_money'],
			            'original_money' => $info['yongjin'],
                        'from_order_id' => $order_info['id'],
			            'latest_money' => $info['yongjin']+$value['no_money'],
			            'msg' => '分佣金额',
			            'add_time' => time()
			        ]);
			        if($proxy_money_log_id <= 0)
			        {
			        	continue;
			        }
			        //更新当前结算信息状态
			        if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
					{
						continue;
					}
				break;
			}
			$balance_ph_count++;
		}
		if($balance_ph_count != count($balance_list))
		{
			Db::rollback();
			echo json_encode(['code' => -100, 'msg' => '结算记录更新失败']);
			exit();
		}
		
		if($status==6&&!empty($params['budan_reason'])){
		    db::name('order_from')->insert(['order_id'=>$params['order_id'],'title'=>$params['budan_reason'],'add_time'=>time(),'techn_id'=>$params['techn']['id']]);
		}

//        增加技师业绩
        $have_result = Db::name('techn_last')->where('techn_id',$params['techn']['id'])->field('total_result')->find();
        $now_result = $have_result['total_result']+$over_result;
        $last_re = Db::name('techn_last')->where('techn_id',$params['techn']['id'])->update(['total_result'=>$now_result]);


        TechnService::TechnPreTimey($params['techn']['id']);
		
		//提交事务
		Db::commit();
		echo json_encode(['code' => 0, 'msg' => '完成成功']);
		
		//走队列
		//创建任务： 项目命名空间\模块\文件夹\控制器@方法
		$job = "app\service\QueuesService@yinsi_close";
		//延时时间
		$delayed_second = 600;
		$queues_data = ['mobile' => $params['techn']['mobile']];
		\think\Queue::later($delayed_second, $job, $queues_data, 'yinsi_close');
		
// 		//从缓存中读取技师与客户绑定的隐私号码信息
//         $yinsi_phone = cache('yinsi_phone_'.$params['techn']['mobile']);
//         if(!empty($yinsi_phone))
//         {
//         	//解绑关系
//         	$args = [
//         		'poolKey' => 'FC100000167170034',
//         		'subsId' => $yinsi_phone['subsId'],
//         		'secretNo' => $yinsi_phone['secretNo']
//         	];
//         	\yinsi\Privacy::UnbindSubscription($args);
//         }
	}

	/**
	 * 拒绝接单
	 */
	public function no_meet()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id'], 'techn_id' => $params['techn']['id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if($order_info['status'] != 1)
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        // 订单支付方式校验
        $pay_log = Db::name('pay_log')->where(['order_id' => $order_info['id'], 'business_type' => 1])->find();
        if(empty($pay_log))
        {
        	echo json_encode(['code' => -100, 'msg' => '支付日志不存在']);
			exit();
        }
        //判断是否为余额支付
        $is_money = false;
        if($pay_log['payment'] == 'MoneyPay')
        {
        	//是
        	$is_money = true;
        }else
        {
        	//否，原路退回
        	// 操作退款
        	$payment_array = PaymentService::$payment_array;
        	$payment = $payment_array[$order_info['payment_id']];
        	$pay_name = 'payment\\'.$payment['payment'];
        	$pay_params = [
        		'order_id'          => $order_info['id'],
        		'order_no'          => $order_info['order_no'],
        		'trade_no'          => $pay_log['trade_no'],
        		'pay_price'         => $order_info['pay_price'],
        		'refund_price'      => $order_info['pay_price'],
        		'client_type'       => $order_info['client_type'],
        		'refund_reason'     => $order_info['order_no'].'订单退款'.$order_info['pay_price'].'元',
        		'pay_time'          => $order_info['pay_time'],
        	];
        	$refund = (new $pay_name($payment['config']['user']))->Refund($pay_params);
        }
        // 退款成功
        if(isset($refund['code']) && $refund['code'] != 0)
        {
            echo json_encode($refund);
			exit();
        }
        // 开启事务
        Db::startTrans();
        //退款日志数据
        $refund_log_data = [];
        // 余额退款
        if($is_money === true)
        {
        	// 获取用户余额
        	$user_info = Db::name('user')->where(['id' => $order_info['user_id']])->find();
        	if(empty($user_info))
        	{
        		Db::rollback();
        		echo json_encode(['code' => -100, 'msg' => '用户不存在']);
			    exit();
        	}
        	// 更新余额数据
        	$money_data = [
	            'money' => Db::raw('money+'.$order_info['pay_price']),
	            'upd_time' => time()
	        ];
	        if(!Db::name('user')->where(['id' => $user_info['id']])->update($money_data))
	        {
	            Db::rollback();
	            echo json_encode(['code' => -100, 'msg' => '余额操作失败']);
			    exit();
	        }
	        //余额日志
	        $money_log_id = Db::name('money_log')->insertGetId([
	            'identity_type' => 'user',
	            'identity_id' => $user_info['id'],
	            'business_type' => 2,
	            'money_type' => 0,
	            'operation_type' => 1,
	            'operation_money' => $order_info['pay_price'],
	            'original_money' => $user_info['money'],
	            'latest_money' => $user_info['money']+$order_info['pay_price'],
	            'msg' => '订单退款',
	            'add_time' => time()
	        ]);
	        if($money_log_id <= 0)
	        {
	            Db::rollback();
	            echo json_encode(['code' => -100, 'msg' => '余额日志添加失败']);
			    exit();
	        }
	        $refund_log_data = [
	        	'order_id' => $order_info['id'],
	        	'trade_no' => '',
	        	'buyer_user' => '',
	        	'refund_price' => $order_info['pay_price'],
	        	'pay_price' => $order_info['pay_price'],
	        	'msg' => '订单退款',
	        	'payment' => $pay_log['payment'],
	        	'payment_name' => $pay_log['payment_name'],
	        	'refundment' => 0,
	        	'business_type' => 1,
	        	'return_params' => '',
	        	'add_time' => time(),
	        	'reason'=>!empty($params['reason'])?$params['reason']:''
	        ];
        }else
        {
        	$refund_log_data = [
        		'order_id' => $order_info['id'],
        		'trade_no' => isset($refund['data']['trade_no']) ? $refund['data']['trade_no'] : '',
        		'buyer_user' => isset($refund['data']['buyer_user']) ? $refund['data']['buyer_user'] : '',
        		'refund_price' => isset($refund['data']['refund_price']) ? $refund['data']['refund_price'] : '',
        		'pay_price' => $order_info['pay_price'],
        		'msg' => '订单退款',
        		'payment' => $pay_log['payment'],
        		'payment_name' => $pay_log['payment_name'],
        		'refundment' => 0,
        		'business_type' => 1,
        		'return_params' => isset($refund['data']['return_params']) ? json_encode($refund['data']['return_params'], JSON_UNESCAPED_UNICODE) : '',
        		'add_time' => time(),
	        	'reason'=>!empty($params['reason'])?$params['reason']:''
        	];
        }
        //写入退款日志
        $refund_log_id = Db::name('refund_log')->insertGetId($refund_log_data);
        if($refund_log_id <= 0)
        {
        	Db::rollback();
        	echo json_encode(['code' => -100, 'msg' => '退款日志添加失败']);
			exit();
        }
        // 更新主订单
        $order_upd_data = [
        	'pay_status' => 2,
        	'refund_price' => $refund_log_data['refund_price'],
        	'status' => 14, //技师拒单
        	'close_time' => time(),
        	'meet_status' => 2,
        	'meet_time' => time(),
        	'techn_is_repair' => $order_info['distance'] <= 20 ? 1 : 0, //技师补单状态(20km以内拒绝，需要补单)
        	'upd_time' => time(),
        ];
        //更新订单状态
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($order_upd_data))
		{
			Db::rollback();
			echo json_encode(['code' => -100, 'msg' => '订单更新失败']);
			exit();
		}
		//添加状态日志
		$status_array = OrderService::$status_array;
		$order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $order_upd_data['status'],
			'msg' => '技师拒单['.$status_array[$order_info['status']]['name'].'-'.$status_array[$order_upd_data['status']]['name'].']',
			'identity_type' => 'techn',
			'identity_id' => $params['techn']['id'],
			'add_time' => time()
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			echo json_encode(['code' => -100, 'msg' => '订单历史状态添加失败']);
			exit();
		}
		//处理结算表
		$balance_data = [
			'status' => 2,
			'upd_time' => time()
		];
		if(!Db::name('balance')->where(['order_id' => $order_info['id'], 'status' => 0])->update($balance_data))
		{
			Db::rollback();
			echo json_encode(['code' => -100, 'msg' => '结算记录更新失败']);
			exit();
		}
		//提交事务
		Db::commit();
		echo json_encode(['code' => 0, 'msg' => '拒单成功']);
		//给用户推送模板消息
		//查询用户的openid
		$user_openid = Db::name('user_weixin')->where(['user_id' => $order_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
		if(!empty($user_openid))
		{
			$tem_msg['touser'] = $user_openid;
			$tem_msg['template_id'] = 'zZ7W-JsnM7OwbWnnuPxodYSCpBrGLOY1X0hKDwFHpT4';
			$tem_msg['url'] = request()->domain().'/h5/pages/order/orderdetail?order_id='.$order_info['id'];
			$tem_msg['data'] = [
				'first' => [
	                'value' => '退款通知',
	                'color' => '#173177'
	            ],
	            'keyword1' => [
	                'value' => $order_info['order_no'],
	                'color' => '#173177'
	            ],
	            'keyword2' => [
	                'value' => $params['techn']['nickname'],
	                'color' => '#173177'
	            ],
	            'keyword3' => [
	                'value' => '技师拒单',
	                'color' => '#173177'
	            ],
	            'keyword4' => [
	                'value' => $order_info['total_price'].'元',
	                'color' => '#173177'
	            ],
	            'remark' => [
	                'value' => '退款'.$refund_log_data['refund_price'].'元，感谢您的使用！',
	                'color' => '#173177'
	            ]
	        ];
	        UserWeixinService::send_wx_web_tem_msg($tem_msg);
		}
        TechnService::TechnPreTimey($params['techn']['id']);
	}

	/**
	 * 技师联系客户
	 */
	public function contact_client()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id'], 'techn_id' => $params['techn']['id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if(!($order_info['status'] >= 2 && $order_info['status'] <= 5))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        if($order_info['status']==6&&time()-$order_info['pre_end_time']>600){
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        //技师与下单人绑定隐私电话
        //查询下单人的电话
        $order_address_info = Db::name('order_address')->where(['order_id' => $order_info['id']])->find();
        //从缓存中读取技师与客户绑定的隐私号码信息
        $yinsi_phone = cache('yinsi_phone_'.$params['techn']['mobile']);
        if(!empty($yinsi_phone))
        {
        	//解绑关系
        	$args = [
        		'poolKey' => 'FC100000167170034',
//        		'poolKey' => 'FC100000168856007',
        		'subsId' => $yinsi_phone['subsId'],
        		'secretNo' => $yinsi_phone['secretNo']
        	];
        	\yinsi\Privacy::UnbindSubscription($args);
        }
        //绑定关系
        $args = [
        	"poolKey" => "FC100000167170034",
//        	"poolKey" => "FC100000168856007",
        	"phoneNoA" => $params['techn']['mobile'],
        	"phoneNoB" => $order_address_info['mobile'],
        	"expiration" => date('Y-m-d H:i:s', time()+(5*60)),
        	"isRecordingEnabled" => true
        ];
        $yinsi_res = \yinsi\Privacy::bindAxb($args);
        if($yinsi_res['code'] != 1)
        {
        	/*echo json_encode(['code' => -1, 'msg' => '请稍后联系']);
            exit();*/
        	$yinsi_res['secretNo'] = $order_address_info['mobile'];
        }else
        {
            //绑定关系存入缓存	
            cache('yinsi_phone_'.$params['techn']['mobile'], $yinsi_res);
        }
        $result['code'] = 0;
		$result['msg'] = '请求成功';
		$result['data'] = $yinsi_res;
		echo json_encode($result);
	}
	
	//报错反馈
	public function order_err(){
	    
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		
		$order_info = Db::name('order')->where(['id' => $params['order_id'], 'techn_id' => $params['techn']['id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        
        // 订单支付方式校验
        $pay_log = Db::name('pay_log')->where(['order_id' => $order_info['id'], 'business_type' => 1])->find();
        if(empty($pay_log))
        {
        	echo json_encode(['code' => -100, 'msg' => '支付日志不存在']);
			exit();
        }
        $refund_price = $order_info['pay_price'];
        $pay_status = 2;
        if($order_info['status'] == 3)
        {
        	//如果技师出发只退服务费用
        	//$refund_price = $order_info['price'];
        	$refund_price = $order_info['pay_price']-$order_info['travel_price'];
        	$pay_status = 3;
        }else if($order_info['status'] == 4)
        {
        	//如果技师到达只退一半服务费用
        	$refund_price = PriceNumberFormat(($order_info['pay_price']-$order_info['travel_price'])/2);
        	$pay_status = 3;
        }
        
        
        //判断是否为余额支付
        $is_money = false;
        if($pay_log['payment'] == 'MoneyPay')
        {
        	//是
        	$is_money = true;
        }else
        {
        	//否，原路退回
        	// 操作退款
        	$payment_array = PaymentService::$payment_array;
        	$payment = $payment_array[$order_info['payment_id']];
        	$pay_name = 'payment\\'.$payment['payment'];
        	$pay_params = [
        		'order_id'          => $order_info['id'],
        		'order_no'          => $order_info['order_no'],
        		'trade_no'          => $pay_log['trade_no'],
        		'pay_price'         => $order_info['pay_price'],
        		'refund_price'      => $refund_price,
        		'client_type'       => $order_info['client_type'],
        		'refund_reason'     => $order_info['order_no'].'订单退款'.$refund_price.'元',
        		'pay_time'          => $order_info['pay_time'],
        	];
        	$refund = (new $pay_name($payment['config']['user']))->Refund($pay_params);
        }
        // 退款成功
        if(isset($refund['code']) && $refund['code'] != 0)
        {
            echo json_encode($refund);
			exit();
        }
        
        // 开启事务
        Db::startTrans();
        
        $order_err_id = Db::name('order_err')->insertGetId([
	            'order_no' => $order_info['order_no'],
	            'techn_id' => $order_info['techn_id'],
	            'reason' => $params['reason'],
	            'add_time' => time()
	        ]);
	        
	     	if(empty($order_err_id))
        	{
        		Db::rollback();
        		echo json_encode(['code' => -100, 'msg' => '添加错误']);
			    exit();
        	}
        //退款日志数据
        $refund_log_data = [];
        // 余额退款
        if($is_money === true)
        {
        	// 获取用户余额
        	$user_info = Db::name('user')->where(['id' => $order_info['user_id']])->find();
        	if(empty($user_info))
        	{
        		Db::rollback();
        		echo json_encode(['code' => -100, 'msg' => '用户不存在']);
			    exit();
        	}
        	// 更新余额数据
        	$money_data = [
	            'money' => Db::raw('money+'.$refund_price),
	            'upd_time' => time()
	        ];
	        if(!Db::name('user')->where(['id' => $user_info['id']])->update($money_data))
	        {
	            Db::rollback();
	            echo json_encode(['code' => -100, 'msg' => '余额操作失败']);
			    exit();
	        }
	        //余额日志
	        $money_log_id = Db::name('money_log')->insertGetId([
	            'identity_type' => 'user',
	            'identity_id' => $user_info['id'],
	            'business_type' => 2,
	            'money_type' => 0,
	            'operation_type' => 1,
	            'operation_money' => $refund_price,
	            'original_money' => $user_info['money'],
	            'latest_money' => $user_info['money']+$refund_price,
	            'msg' => '订单退款',
	            'add_time' => time()
	        ]);
	        if($money_log_id <= 0)
	        {
	            Db::rollback();
	            echo json_encode(['code' => -100, 'msg' => '余额日志添加失败']);
			    exit();
	        }
	        $refund_log_data = [
	        	'order_id' => $order_info['id'],
	        	'trade_no' => '',
	        	'buyer_user' => '',
	        	'refund_price' => $refund_price,
	        	'pay_price' => $order_info['pay_price'],
	        	'msg' => '订单退款',
	        	'payment' => $pay_log['payment'],
	        	'payment_name' => $pay_log['payment_name'],
	        	'refundment' => 0,
	        	'business_type' => 1,
	        	'return_params' => '',
	        	'add_time' => time(),
        		'uid'=>$order_info['user_id'],
			    'reason'=>empty($params['reason'])?'':$params['reason'],
			    'day'=>date('Y-m-d')
	        ];
        }else
        {
        	$refund_log_data = [
        		'order_id' => $order_info['id'],
        		'trade_no' => isset($refund['data']['trade_no']) ? $refund['data']['trade_no'] : '',
        		'buyer_user' => isset($refund['data']['buyer_user']) ? $refund['data']['buyer_user'] : '',
        		'refund_price' => isset($refund['data']['refund_price']) ? $refund['data']['refund_price'] : '',
        		'pay_price' => $order_info['pay_price'],
        		'msg' => '订单退款',
        		'payment' => $pay_log['payment'],
        		'payment_name' => $pay_log['payment_name'],
        		'refundment' => 0,
        		'business_type' => 1,
        		'return_params' => isset($refund['data']['return_params']) ? json_encode($refund['data']['return_params'], JSON_UNESCAPED_UNICODE) : '',
        		'add_time' => time(),
        		'uid'=>$order_info['user_id'],
			    'reason'=>empty($params['reason'])?'':$params['reason'],
			    'day'=>date('Y-m-d')
        	];
        }
        //写入退款日志
        $refund_log_id = Db::name('refund_log')->insertGetId($refund_log_data);
        if($refund_log_id <= 0)
        {
        	Db::rollback();
        	echo json_encode(['code' => -100, 'msg' => '退款日志添加失败']);
			exit();
        }
        // 更新主订单
        $order_upd_data = [
        	'pay_status' => $pay_status,
        	'refund_price' => $refund_log_data['refund_price'],
        	'status' => 13, //技师退款
        	'close_time' => time(),
        	'upd_time' => time(),
        ];
        //更新订单状态
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($order_upd_data))
		{
			Db::rollback();
			echo json_encode(['code' => -100, 'msg' => '订单更新失败']);
			exit();
		}
		//添加状态日志
		$status_array = OrderService::$status_array;
		$order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $order_upd_data['status'],
			'msg' => '退款['.$status_array[$order_info['status']]['name'].'-'.$status_array[$order_upd_data['status']]['name'].']',
			'identity_type' => 'user',
			'identity_id' => $order_info['user_id'],
			'add_time' => time(),
			'reason'=>empty($params['reason'])?'':$params['reason']
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			echo json_encode(['code' => -100, 'msg' => '订单历史状态添加失败']);
			exit();
		}
		//根据状态处理结算日志
		if($order_info['status'] == 3 || $order_info['status'] == 4)
		{
			//处理结算信息
			$balance_list = Db::name('balance')->where(['order_id' => $order_info['id'], 'status' => 0])->select();
			if(empty($balance_list))
			{
				Db::rollback();
				echo json_encode(['code' => -1, 'msg' => '结算数据不存在']);
	            exit();
			}
			$balance_ph_count = 0;
			foreach($balance_list as $key => $value)
			{
				switch($value['identity_type'])
				{
					//技师
					case 'techn':
					    if($order_info['status'] == 3)
					    {
					    	//如果技师出发只退服务费用
					    	if($value['balance_type'] != 1)
					    	{
							    //获取技师余额
						        $techn_info = Db::name('techn')->where(['id' => $value['identity_id']])->find();
						        if(empty($techn_info))
								{
									continue;
								}
								// 更新余额数据
								$techn_money_data = [
									'money' => Db::raw('money+'.$value['no_money']),
						            'upd_time' => time()
								];
								if(!Db::name('techn')->where(['id' => $techn_info['id']])->update($techn_money_data))
								{
									continue;
								}
								//技师余额日志
								$techn_money_log_id = Db::name('money_log')->insertGetId([
						            'identity_type' => 'techn',
						            'identity_id' => $techn_info['id'],
						            'business_type' => $value['balance_type'] == 2 ? 4 : 5,
						            'money_type' => 0,
						            'operation_type' => 1,
						            'operation_money' => $value['no_money'],
						            'original_money' => $techn_info['money'],
						            'latest_money' => $techn_info['money']+$value['no_money'],
						            'msg' => '技师'.($value['balance_type'] == 2 ? '出行' : '服务').'费用',
						            'add_time' => time()
						        ]);
						        if($techn_money_log_id <= 0)
						        {
						        	continue;
						        }
						        //更新当前结算信息状态
						        if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
								{
									continue;
								}
							}else
							{
								//更新当前结算信息状态
						        if(!Db::name('balance')->where(['id' => $value['id']])->update(['status' => 2, 'upd_time' => time()]))
								{
									continue;
								}
							}
						}else
						{
							//如果技师到达只退一半服务费用
							if($value['balance_type'] == 1)
							{
								$value['no_money'] = PriceNumberFormat($value['no_money']/2);
							}
							$techn_info = Db::name('techn')->where(['id' => $value['identity_id']])->find();
					        if(empty($techn_info))
							{
								continue;
							}
							// 更新余额数据
							$techn_money_data = [
								'money' => Db::raw('money+'.$value['no_money']),
					            'upd_time' => time()
							];
							if(!Db::name('techn')->where(['id' => $techn_info['id']])->update($techn_money_data))
							{
								continue;
							}
							//技师余额日志
							$techn_money_log_id = Db::name('money_log')->insertGetId([
					            'identity_type' => 'techn',
					            'identity_id' => $techn_info['id'],
					            'business_type' => $value['balance_type'] == 2 ? 4 : 5,
					            'money_type' => 0,
					            'operation_type' => 1,
					            'operation_money' => $value['no_money'],
					            'original_money' => $techn_info['money'],
					            'latest_money' => $techn_info['money']+$value['no_money'],
					            'msg' => '技师'.($value['balance_type'] == 2 ? '出行' : '服务').'费用',
					            'add_time' => time()
					        ]);
					        if($techn_money_log_id <= 0)
					        {
					        	continue;
					        }
					        //更新当前结算信息状态
					        if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
							{
								continue;
							}
						}
					break;
					//机构
					case 'proxy':
					    if($order_info['status'] == 3)
					    {
					    	//如果技师出发只退服务费用
					    	//更新当前结算信息状态
					        if(!Db::name('balance')->where(['id' => $value['id']])->update(['status' => 2, 'upd_time' => time()]))
							{
								continue;
							}
					    }else
					    {
					    	//如果技师到达只退一半服务费用
					    	$value['no_money'] = PriceNumberFormat($value['no_money']/2);
					    	//获取机构余额
					    	$proxy_info = Db::name('proxy')->where(['proxy_id' => $value['identity_id']])->find();
					    	if(empty($proxy_info))
							{
								continue;
							}
							// 更新余额数据
							$proxy_money_data = [
								'money' => Db::raw('money+'.$value['no_money']),
						        'upd_time' => time()
							];
							if(!Db::name('proxy')->where(['proxy_id' => $proxy_info['proxy_id']])->update($proxy_money_data))
							{
								continue;
							}
							//机构余额日志
							$proxy_money_log_id = Db::name('money_log')->insertGetId([
						        'identity_type' => 'proxy',
						        'identity_id' => $proxy_info['proxy_id'],
						        'business_type' => 5,
						        'money_type' => 0,
						        'operation_type' => 1,
						        'operation_money' => $value['no_money'],
						        'original_money' => $proxy_info['money'],
						        'latest_money' => $proxy_info['money']+$value['no_money'],
						        'msg' => '机构服务分成费用',
						        'add_time' => time()
						    ]);
						    if($proxy_money_log_id <= 0)
						    {
						    	continue;
						    }
						    //更新当前结算信息状态
						    if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
							{
								continue;
							}
					    }
					break;
					//系统
					case 'system':
					    if($order_info['status'] == 3)
					    {
					    	//如果技师出发只退服务费用
					    	//更新当前结算信息状态
					        if(!Db::name('balance')->where(['id' => $value['id']])->update(['status' => 2, 'upd_time' => time()]))
							{
								continue;
							}
					    }else
					    {
					    	//如果技师到达只退一半服务费用
					    	if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => PriceNumberFormat($value['no_money']/2), 'status' => 1, 'upd_time' => time()]))
							{
								continue;
							}
					    }
					break;
				}
				$balance_ph_count++;
			}
			if($balance_ph_count != count($balance_list))
			{
				Db::rollback();
				echo json_encode(['code' => -100, 'msg' => '结算记录更新失败']);
				exit();
			}
		}else
		{
			//技师未出发结算状态关闭
			$balance_data = [
				'status' => 2,
				'upd_time' => time()
			];
			if(!Db::name('balance')->where(['order_id' => $order_info['id'], 'status' => 0])->update($balance_data))
			{
				Db::rollback();
				echo json_encode(['code' => -100, 'msg' => '结算记录更新失败']);
				exit();
			}
		}
		//提交事务
		Db::commit();
		echo json_encode(['code' => 0, 'msg' => '退款成功']);
		//发送模板消息
		//查询技师信息
		$techn_info = Db::name('techn')->where(['id' => $order_info['techn_id']])->find();
		if(!empty($techn_info))
		{
		    
            TechnService::TechnPreTimey($order_info['techn_id']);
			//查询技师关联用户公众号的openid
			$techn_openid = Db::name('user_weixin')->where(['user_id' => $techn_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
			//给技师推送模板消息
			if(!empty($techn_openid))
			{
			    
			//给用户推送模板消息
			//查询用户的openid
			$user_openid = Db::name('user_weixin')->where(['user_id' => $order_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
			if(!empty($user_openid))
			{
				$tem_msg = [];
				$tem_msg['touser'] = $user_openid;
				$tem_msg['template_id'] = 'zZ7W-JsnM7OwbWnnuPxodYSCpBrGLOY1X0hKDwFHpT4';
				$tem_msg['url'] = request()->domain().'/h5/pages/order/orderdetail?order_id='.$order_info['id'];
				$tem_msg['data'] = [
					'first' => [
		                'value' => '退款通知',
		                'color' => '#173177'
		            ],
		            'keyword1' => [
		                'value' => $order_info['order_no'],
		                'color' => '#173177'
		            ],
		            'keyword2' => [
		                'value' => $techn_info['nickname'],
		                'color' => '#173177'
		            ],
		            'keyword3' => [
		                'value' => $params['reason'],
		                'color' => '#173177'
		            ],
		            'keyword4' => [
		                'value' => $order_info['total_price'].'元',
		                'color' => '#173177'
		            ],
		            'remark' => [
		                'value' => '退款'.$refund_log_data['refund_price'].'元，感谢您的使用！',
		                'color' => '#173177'
		            ]
				];
				UserWeixinService::send_wx_web_tem_msg($tem_msg);
			}
		}
        
        
		}
		
	}
}